package com.buyi.easyhome.widget

import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.util.TypedValue
import android.widget.RemoteViews
import com.buyi.easyhome.R


/**
 * Implementation of App Widget functionality.
 */
class ClockAppWidget : AppWidgetProvider() {
    override fun onUpdate(
        context: Context,
        appWidgetManager: AppWidgetManager,
        appWidgetIds: IntArray
    ) {
        // There may be multiple widgets active, so update all of them
        updateAppWidget(context, appWidgetManager)
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        super.onReceive(context, intent)
        if (intent != null) {
            if (AppWidgetManager.ACTION_APPWIDGET_UPDATE == intent.action) {
                if (context != null) {
                    // 获取 AppWidgetManager 实例
                    val appWidgetManager = AppWidgetManager.getInstance(context)
                    updateAppWidget(context, appWidgetManager)
                }
            }
        }
    }
}

internal fun updateAppWidget(
    context: Context,
    appWidgetManager: AppWidgetManager,
    clazz: Class<*> = ClockAppWidget::class.java
) {
    // Construct the RemoteViews object
    val views = RemoteViews(context.packageName, R.layout.clock_app_widget)


    // 创建一个空的 PendingIntent
    val emptyIntent = Intent()
    val pendingIntent = PendingIntent.getActivity(context, 0, emptyIntent, PendingIntent.FLAG_IMMUTABLE)

    // 将 PendingIntent 设置到 Widget 的点击事件
    views.setOnClickPendingIntent(R.id.timeText, pendingIntent)

    // 计算字体大小
    val textSize = (context.resources.displayMetrics.widthPixels / 5).toFloat() * 1.4f

    views.setTextViewTextSize(R.id.timeText, TypedValue.COMPLEX_UNIT_PX, textSize)

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(ComponentName(context, clazz), views)
}